<template>
  <div class="article-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="articleStore.searchForm">
        <el-form-item class="el-form-item">
          <el-input
              v-model="articleStore.searchForm.keyword"
              placeholder="搜索文章"
          />
        </el-form-item>
        <el-form-item style="width: 100px" class="el-form-item">
          <el-select
              v-model="articleStore.searchForm.status"
              placeholder="文章状态"
          >
            <el-option label="全部" :value="-1"/>
            <el-option label="已发布" :value="1"/>
            <el-option label="已下架" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item class="el-form-item">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSync">立即触发同步文章数据</el-button>
          <el-button type="primary" @click="handleView">立即触发同步浏览数据</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 批量操作栏 -->
    <div class="batch-operations" v-if="selectedArticles.length > 0">
      <el-alert
          title="已选择"
          type="info"
          :description="`已选择 ${selectedArticles.length} 篇文章`"
          show-icon
      >
        <template #default>
          <div class="operations">
            {{selectedArticles.length}}
            <el-dropdown @command="handleBatchSource">
              <el-button type="primary" link>修改来源</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="admin">管理员发布</el-dropdown-item>
                  <el-dropdown-item command="crawler">爬虫抓取</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 批量置顶操作 -->
            <el-dropdown @command="handleBatchTop">
              <el-button type="primary" link>置顶操作</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ isTop: true, order: 0 }">设为置顶</el-dropdown-item>
                  <el-dropdown-item :command="{ isTop: false }">取消置顶</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 批量热门操作 -->
            <el-dropdown @command="handleBatchHot">
              <el-button type="warning" link>热门操作</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ isHot: true, order: 0 }">设为热门</el-dropdown-item>
                  <el-dropdown-item :command="{ isHot: false }">取消热门</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 修改状态操作 -->
            <el-dropdown @command="handleBatchStatus">
              <el-button type="primary" link>修改状态</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="0">草稿</el-dropdown-item>
                  <el-dropdown-item :command="1">发布</el-dropdown-item>
                  <el-dropdown-item :command="2">下架</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 批量推荐操作 -->
            <el-dropdown @command="handleBatchRecommend">
              <el-button type="success" link>推荐操作</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ isRecommend: true, order: 0 }">设为推荐</el-dropdown-item>
                  <el-dropdown-item :command="{ isRecommend: false }">取消推荐</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <el-button type="danger" link @click="handleBatchDelete">
              批量删除
            </el-button>
          </div>
        </template>
      </el-alert>
    </div>

    <!-- 文章列表 -->
    <el-table
        style="width: 100%"
        :data="articleStore.articleList"
        v-loading="articleStore.loading"
        @selection-change="handleSelectionChange"
        class="article-management-table"
    >
      <!-- 选择列 -->
      <el-table-column type="selection" width="55" />

      <!-- 标题列 -->
      <el-table-column
          prop="title"
          label="标题"
          min-width="200"
          show-overflow-tooltip
      >
        <template #default="{ row }">
          <div class="title-cell">
            <span class="title-text">{{ row.title }}</span>
          </div>
        </template>
      </el-table-column>

      <!-- 来源列 -->
      <el-table-column label="来源" width="100" align="center">
        <template #default="{ row }">
          <el-tag
              :type="row.source === 'admin' ? 'success' : 'warning'"
              class="source-tag"
              effect="light"
              size="small"
          >
            {{ row.source === 'admin' ? '管理员' : (row.source === 'crawler' ? '爬虫' : '未知来源') }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 置顶列 -->
      <el-table-column label="置顶" width="200" align="center">
        <template #default="{ row }">
          <div class="control-group">
            <el-switch
                v-model="row.isTop"
                @change="(val) => handleToggleTop(row, val)"
                active-color="#409EFF"
                class="custom-switch"
            />
            <el-input-number
                v-if="row.isTop"
                v-model="row.topOrder"
                :min="0"
                :max="99"
                size="small"
                class="order-input"
                @change="(val) => handleUpdateOrder(row, 'top', val)"
                controls-position="right"
            />
          </div>
        </template>
      </el-table-column>

      <!-- 热门列 -->
      <el-table-column label="热门" width="200" align="center">
        <template #default="{ row }">
          <div class="control-group">
            <el-switch
                v-model="row.isHot"
                @change="(val) => handleToggleHot(row, val)"
                active-color="#E6A23C"
                class="custom-switch"
            />
            <el-input-number
                v-if="row.isHot"
                v-model="row.hotOrder"
                :min="0"
                :max="99"
                size="small"
                class="order-input"
                @change="(val) => handleUpdateOrder(row, 'hot', val)"
                controls-position="right"
            />
          </div>
        </template>
      </el-table-column>

      <!-- 推荐列 -->
      <el-table-column label="推荐" width="200" align="center">
        <template #default="{ row }">
          <div class="control-group">
            <el-switch
                v-model="row.isRecommend"
                @change="(val) => handleToggleRecommend(row, val)"
                active-color="#67C23A"
                class="custom-switch"
            />
            <el-input-number
                v-if="row.isRecommend"
                v-model="row.recommendOrder"
                :min="0"
                :max="99"
                size="small"
                class="order-input"
                @change="(val) => handleUpdateOrder(row, 'recommend', val)"
                controls-position="right"
            />
          </div>
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column
          label="操作"
          width="300"
          fixed="right"
          align="center"
      >
        <template #default="{ row }">
          <div class="action-buttons">
            <el-button
                type="info"
                class="action-btn preview-btn"
                size="small"
                @click="handlePreview(row)"
            >
              <el-icon><View /></el-icon>
              预览
            </el-button>
            <el-button
                type="primary"
                class="action-btn edit-btn"
                size="small"
                @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>

            <el-button
                v-if="row.status === 0"
                type="success"
                class="action-btn publish-btn"
                size="small"
                @click="handlePublish(row)"
            >
              <el-icon><Upload /></el-icon>
              发布
            </el-button>

            <el-button
                v-if="row.status === 1"
                type="warning"
                class="action-btn unpublish-btn"
                size="small"
                @click="handleUnpublish(row)"
            >
              <el-icon><Download /></el-icon>
              下架
            </el-button>

            <el-button
                v-if="row.status === 2"
                type="warning"
                class="action-btn publish-btn"
                size="small"
                @click="handlePublish(row)"
            >
              <el-icon><Upload /></el-icon>
              上架
            </el-button>

            <el-button
                type="danger"
                class="action-btn delete-btn"
                size="small"
                @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="articleStore.currentPage"
        v-model:page-size="articleStore.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :layout="'sizes, prev, pager, next, jumper, total'"
        :total="articleStore.total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
    />

    <!-- 预览对话框 -->
    <el-dialog
        v-model="previewVisible"
        title="文章预览"
        width="80%"
        class="preview-dialog"
        destroy-on-close
    >
      <div class="preview-container">
        <div class="preview-tools">
          <el-radio-group v-model="previewDevice" size="small">
            <el-radio-button label="desktop">
              <el-icon><Monitor /></el-icon>
              桌面端
            </el-radio-button>
            <el-radio-button label="tablet">
              <el-icon><Notebook /></el-icon>
              平板端
            </el-radio-button>
            <el-radio-button label="mobile">
              <el-icon><Iphone /></el-icon>
              手机端
            </el-radio-button>
          </el-radio-group>
        </div>

        <div
            class="preview-frame"
            :class="previewDevice"
        >
          <div class="article">
            <header class="article-header">
              <h1 class="article-title">{{ previewArticle.title }}</h1>
              <div class="article-meta">
                <span class="author">By {{ previewArticle.author }}</span>
                <span class="divider">•</span>
                <span class="timestamp">{{ formatDate(previewArticle.updateTime) }}</span>
              </div>
            </header>

            <div class="article-content">
              <div class="admin-content" v-html="previewArticle.contentHtml"></div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted,ref } from 'vue'
import { useRouter } from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Edit, Upload, Download, Delete, View, Iphone, Monitor, Notebook} from '@element-plus/icons-vue'
import { useArticleStore } from '@/stores/adminArticle'
import { formatDate } from '@/utils/date'
import { getArticlePreview  } from '@/api/article'
import { syncData, syncView } from '@/api/config'

const selectedArticles = ref([])

const router = useRouter()

const articleStore = useArticleStore()

// 预览相关的响应式变量
const previewVisible = ref(false)
const previewArticle = ref({})
const previewDevice = ref('desktop')

// 预览处理函数
const handlePreview = async (row) => {
  try {
    const { data } = await getArticlePreview(row.id)
    previewArticle.value = data
    previewVisible.value = true
  } catch (error) {
    ElMessage.error('获取预览内容失败')
  }
}

// 选择变化处理
const handleSelectionChange = (articles) => {
  selectedArticles.value = articles
}

// 批量修改来源
const handleBatchSource = async (source) => {
  try {
    await ElMessageBox.confirm(
        `确认将选中的 ${selectedArticles.value.length} 篇文章修改为${source === 'admin' ? '管理员发布' : '爬虫抓取'}吗？`
    )

    await articleStore.batchUpdateSource(
        selectedArticles.value.map(article => article.id),
        source
    )
    await articleStore.fetchArticleList()
    ElMessage.success('修改成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('修改失败')
    }
  }
}

// 批量修改状态
const handleBatchStatus = async (status) => {
  const statusText = {
    0: '草稿',
    1: '发布',
    2: '下架'
  }

  try {
    await ElMessageBox.confirm(
        `确认将选中的 ${selectedArticles.value.length} 篇文章修改为${statusText[status]}状态吗？`
    )

    await articleStore.batchUpdateStatus(
        selectedArticles.value.map(article => article.id),
        status
    )
    await articleStore.fetchArticleList()
    ElMessage.success('修改成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('修改失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
        `确认删除选中的 ${selectedArticles.value.length} 篇文章吗？此操作不可恢复！`
    )

    await articleStore.batchRemoveArticles(
        selectedArticles.value.map(article => article.id)
    )
    await articleStore.fetchArticleList()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 搜索处理
const handleSearch = () => {
  articleStore.currentPage = 1
  articleStore.fetchArticleList()
}

const handleReset = () => {
  articleStore.resetSearch()
  handleSearch()
}

const handleSync = () => {
  syncData()
}

const handleView = () => {
  syncView()
}

// 分页处理
const handlePageChange = () => {
  articleStore.fetchArticleList()
}

const handleSizeChange = (val) => {
  articleStore.pageSize = val;
  handleSearch();
}

// 操作处理
const handleEdit = (row) => {
  router.push(`/admin-articles/edit/${row.id}`)
}

const handlePublish = async (row) => {
  try {
    await articleStore.updateStatus(row.id, 1)
    await articleStore.fetchArticleList()
  } catch {
    // 错误已在 store 中处理
  }
}

const handleUnpublish = async (row) => {
  try {
    await articleStore.updateStatus(row.id, 2)
    await articleStore.fetchArticleList()
  } catch {
    // 错误已在 store 中处理
  }
}

const handleToggleTop = async (row, value) => {
  try {
    await articleStore.toggleTop(row.id, value, row.topOrder == null ? 0 : row.topOrder)
    await articleStore.fetchArticleList()
  } catch {
    row.isTop = !value
  }
}

const handleToggleHot = async (row, value) => {
  try {
    await articleStore.toggleHot(row.id, value, row.hotOrder == null ? 0 : row.hotOrder)
    await articleStore.fetchArticleList()
  } catch {
    row.isHot = !value
  }
}

const handleToggleRecommend = async (row, value) => {
  try {
    await articleStore.toggleRecommend(row.id, value, row.recommendOrder == null ? 0 : row.recommendOrder)
    await articleStore.fetchArticleList()
  } catch {
    row.isRecommend = !value
  }
}

const handleUpdateOrder = async (row, type, value) => {
  try {
    switch (type) {
      case 'top':
        await articleStore.toggleTop(row.id, true, value)
        break
      case 'hot':
        await articleStore.toggleHot(row.id, true, value)
        break
      case 'recommend':
        await articleStore.toggleRecommend(row.id, true, value)
        break
    }
    await articleStore.fetchArticleList()
  } catch {
    // 操作失败时恢复原值
    switch (type) {
      case 'top':
        row.topOrder = row.originTopOrder
        break
      case 'hot':
        row.hotOrder = row.originHotOrder
        break
      case 'recommend':
        row.recommendOrder = row.originRecommendOrder
        break
    }
  }
}


const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该文章?')
    await articleStore.removeArticle(row.id)
    await articleStore.fetchArticleList()
  } catch {
    // 取消删除或错误已在 store 中处理
  }
}

// 批量置顶处理
const handleBatchTop = async (command) => {
  try {
    await ElMessageBox.confirm(
        `确认${command.isTop ? '设置' : '取消'}选中的 ${selectedArticles.value.length} 篇文章${command.isTop ? '为' : '的'}置顶状态吗？`
    )

    await articleStore.updateArticlesTop(
        selectedArticles.value.map(article => article.id),
        command.isTop,
        command.order
    )
    await articleStore.fetchArticleList()
    ElMessage.success(`${command.isTop ? '设置' : '取消'}置顶成功`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 批量热门处理
const handleBatchHot = async (command) => {
  try {
    await ElMessageBox.confirm(
        `确认${command.isHot ? '设置' : '取消'}选中的 ${selectedArticles.value.length} 篇文章${command.isHot ? '为' : '的'}热门状态吗？`
    )

    await articleStore.updateArticlesHot(
        selectedArticles.value.map(article => article.id),
        command.isHot,
        command.order
    )
    await articleStore.fetchArticleList()
    ElMessage.success(`${command.isHot ? '设置' : '取消'}热门成功`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 批量推荐处理
const handleBatchRecommend = async (command) => {
  try {
    await ElMessageBox.confirm(
        `确认${command.isRecommend ? '设置' : '取消'}选中的 ${selectedArticles.value.length} 篇文章${command.isRecommend ? '为' : '的'}推荐状态吗？`
    )

    await articleStore.updateArticlesRecommend(
        selectedArticles.value.map(article => article.id),
        command.isRecommend,
        command.order
    )
    await articleStore.fetchArticleList()
    ElMessage.success(`${command.isRecommend ? '设置' : '取消'}推荐成功`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

onMounted(() => {
  articleStore.fetchArticleList()
})

</script>

<style scoped>

.article-management-table {
  /* 确保表格容器可以水平滚动 */
  overflow-x: auto;
}

/* 优化固定列的样式 */
:deep(.el-table .el-table__fixed-right) {
  height: 100% !important;
  /* 添加阴影效果 */
  box-shadow: -6px 0 6px -4px rgba(0,0,0,.12);
}

/* 确保操作按钮在固定列中正确显示 */
.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
}

.preview-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.preview-container {
  background: #f5f7fa;
  min-height: 70vh;
  position: relative;
}

.preview-tools {
  padding: 12px;
  border-bottom: 1px solid #dcdfe6;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 1;
  text-align: center;
}

.preview-frame {
  margin: 0 auto;
  background: #fff;
  transition: all 0.3s;
  overflow-y: auto;
  max-height: 70vh;

  &.desktop {
    width: 80%;
    padding: 20px 40px;
  }

  &.tablet {
    width: 768px;
    padding: 20px 30px;
    margin-top: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }

  &.mobile {
    width: 375px;
    padding: 15px;
    margin-top: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
}

.article-header {
  text-align: center;
  margin-bottom: 30px;

  .article-title {
    font-size: 2em;
    margin-bottom: 15px;
  }

  .article-meta {
    color: #666;
    font-size: 0.9em;

    .divider {
      margin: 0 8px;
    }
  }
}

.article-content {
  line-height: 1.8;
  font-size: 16px;

  :deep(img) {
    max-width: 100%;
    height: auto;
    margin: 10px auto;
    display: block;
  }

  :deep(p) {
    margin: 1em 0;
  }

  :deep(h2) {
    margin: 1.5em 0 1em;
    font-size: 1.5em;
    color: #333;
  }
}

:root {
  --primary-color: #409EFF;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --font-color: #303133;

  /* Layout Variables */
  --border-radius: 8px;
  --border-radius-sm: 4px;
  --box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  --box-shadow-hover: 0 4px 16px rgba(0, 0, 0, 0.15);
  --padding: 12px;
  --gap: 8px;
  --transition: all 0.3s ease;
}

.el-form-item{
  margin: 20px;
}
.article-list {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 搜索栏样式 */
.search-bar {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: var(--gap);
  padding: var(--padding);
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
}

.search-bar .el-form-item {
  margin-right: var(--gap);
}

.batch-operations {
  margin-bottom: 20px;
}

.batch-operations .el-alert {
  border-radius: var(--border-radius);
}

.operations {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-left: 16px;
  align-items: center;
}

.operations .el-button {
  font-weight: 500;
  padding: 6px 12px;
}

/* 表格样式 */
::v-deep(.el-table) {
  border-radius: var(--border-radius);
  overflow: hidden;
  box-shadow: var(--box-shadow);
  transition: var(--transition);
}

::v-deep(.el-table:hover) {
  box-shadow: var(--box-shadow-hover);
}

::v-deep(.el-table th) {
  background-color: #f5f7fa !important;
  font-weight: 600;
  color: var(--font-color);
  padding: 12px 0;
  text-align: center;
}

::v-deep(.el-table td) {
  padding: 16px 0;
  text-align: center;
}

/* 标题单元格样式 */
.title-cell .title-text {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--font-color);
  font-weight: 500;
  transition: var(--transition);
}

/* 来源标签样式 */
.source-tag {
  padding: 4px 12px;
  border-radius: 16px;
  font-weight: 500;
}

/* 控制组样式 */
.control-group {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--gap);
}

.control-group .custom-switch {
  transform: scale(0.9);
}

.control-group .order-input {
  width: 90px;
}

::v-deep(.order-input .el-input__inner) {
  padding: 0 var(--gap);
  text-align: center;
}

/* 批量操作样式 */
.batch-operations {
  margin-bottom: 16px;
}

.operations {
  display: flex;
  gap: 16px;
  margin-left: 16px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: var(--gap);
  justify-content: center;
}

.action-buttons .action-btn {
  padding: 6px 12px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  border-radius: var(--border-radius);
  transition: all 0.3s;
}

.action-buttons .action-btn .el-icon {
  font-size: 14px;
}

.action-buttons .action-btn:hover {
  transform: translateY(-1px);
}

.action-buttons .edit-btn {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}

.action-buttons .publish-btn {
  background-color: var(--success-color);
  border-color: var(--success-color);
}

.action-buttons .unpublish-btn {
  background-color: var(--warning-color);
  border-color: var(--warning-color);
}

.action-buttons .delete-btn {
  background-color: var(--danger-color);
  border-color: var(--danger-color);
}

/* 分页样式 */
::v-deep(.el-pagination) {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
  }

  .action-buttons {
    flex-wrap: wrap;
  }

  .control-group {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
